import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  if (store.state.user.token) {
    config.headers.Authorization = `Bearer ${store.state.user.token}`
  }
  return config
})

// response interceptor
// TODO 清除 console 的插件?
service.interceptors.response.use(response => {
  return response.data
}, error => {
  if (error.response?.data?.error === 'Unauthorized') {
    Message.error('登录已失效')
    store.dispatch('user/logout')
    router.push('/login')
  }
})

export default service
